<?php
include 'cookie.php';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $current_org['cnorg'] ? $current_org['cnorg'].' - ' : ''; ?>AIGC素材库</title>
    <link rel="stylesheet" href="https://cdn.staticfile.net/font-awesome/6.7.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.staticfile.net/tailwindcss/2.2.9/tailwind.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <script src="https://cdn.staticfile.net/motion.js/0.3.0/motion.min.js"></script>
    <!-- <link rel="stylesheet" media="all" href="styles.css" /> -->
    <style>
        @import "styles.css";
    </style>
</head>
<body class="font-sans antialiased transition-colors duration-300 light-mode">
    <!-- 导航栏 -->
    <nav class="navbar sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0 flex items-center">
                        <div class="w-10 h-10 bg-gradient-to-r from-indigo-500 to-purple-600 rounded-xl flex items-center justify-center">
                            <i class="fas fa-robot text-white text-lg"></i>
                        </div>
                        <h1 class="text-xl font-bold text-gray-900 dark:text-white ml-3"><?php echo $current_org['cnorg'] ? $current_org['cnorg'].' - ' : ''; ?>AI素材库</h1>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <!-- 类别筛选 -->
                    <div id="category-filter" class="hidden md:block">
                        <div class="ml-4 flex items-center space-x-3" id="category-buttons">
                            <?php
                            // 获取所有类别
                            $categories = ['根目录'];
                            $tempPath = $_COOKIE['enorg'] . '-output';
                            $excludedFolders = ['BizyAIR', 'OR', 'temp', 'CP', 'GEO', 'downloads', 'temp']; // 排除的文件夹
                            
                            if (is_dir($tempPath)) {
                                $items = scandir($tempPath);
                                foreach ($items as $item) {
                                    if ($item != '.' && $item != '..' && is_dir($tempPath . '/' . $item) && !in_array($item, $excludedFolders)) {
                                        $categories[] = $item;
                                    }
                                }
                            }
                            
                            // 输出类别按钮
                            echo '<button class="category-btn active" data-category="根目录">根目录</button>';
                            
                            foreach ($categories as $category) {
                                if ($category !== '根目录' && !in_array($category, $excludedFolders)) {
                                    echo '<button class="category-btn" data-category="' . htmlspecialchars($category) . '">' . htmlspecialchars($category) . '</button>';
                                }
                            }
                            ?>
                        </div>
                    </div>
                    
                    <!-- 模式切换 -->
                    <button id="theme-toggle" class="theme-toggle">
                        <i class="fas fa-moon"></i>
                    </button>
                    
                    <!-- 返回图像反推按钮 -->
                    <button id="back-to-wd" class="hidden md:flex items-center px-4 py-2 rounded-lg text-sm font-medium text-white bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all duration-300 shadow-lg" onclick="window.location.href='WD/txt.php?login=<?php echo $login_org; ?>'">
                        <i class="fas fa-arrow-left mr-2"></i>
                        图像反推
                    </button>
                    
                    <!-- 移动端菜单按钮 -->
                    <button class="md:hidden p-2 rounded-lg text-gray-500 hover:text-gray-900 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-white dark:hover:bg-gray-700" id="mobile-menu-button">
                        <i class="fas fa-bars"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 移动端菜单 -->
        <div class="md:hidden hidden" id="mobile-menu">
            <div class="px-4 pt-4 pb-4 space-y-2 sm:px-6" id="mobile-category-buttons">
                <?php
                echo '<button class="w-full text-left px-4 py-3 rounded-lg bg-indigo-100 dark:bg-indigo-900 text-indigo-800 dark:text-indigo-200 category-btn active" data-category="根目录">根目录</button>';
                
                foreach ($categories as $category) {
                    if ($category !== '根目录' && !in_array($category, $excludedFolders)) {
                        echo '<button class="w-full text-left px-4 py-3 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 category-btn" data-category="' . htmlspecialchars($category) . '">' . htmlspecialchars($category) . '</button>';
                    }
                }
                ?>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <!-- 标题 -->
        <div class="mb-10 text-center">
            <h2 class="text-4xl font-bold text-gray-900 dark:text-white mb-4">反推图展示</h2>
            <p class="text-xl text-gray-600 dark:text-gray-300 max-w-3xl mx-auto">收集整理内部图片素材，一次反推，多次受益</p>
        </div>
        
        <!-- 作品网格 -->
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-6" id="gallery-grid">
            <?php
            // 获取作品数据
            $works = [];
            $tempPath = $_COOKIE['enorg'] . '-output';
            $excludedFolders = ['BizyAIR', 'OR', 'temp', 'CP', 'GEO', 'downloads', 'temp']; // 排除的文件夹
            
            // 检查output目录是否存在
            if (is_dir($tempPath)) {
                // 首先处理根目录下的文件
                $rootFiles = scandir($tempPath);
                $imageFiles = [];
                $txtFiles = [];
                
                // 分离图片和txt文件
                foreach ($rootFiles as $file) {
                    if ($file != '.' && $file != '..') {
                        $extension = pathinfo($file, PATHINFO_EXTENSION);
                        if (in_array($extension, ['webp', 'jpg', 'png', 'jpeg'])) {
                            $imageFiles[] = $file;
                        } elseif ($extension === 'txt') {
                            $txtFiles[] = $file;
                        }
                    }
                }
                
                // 匹配同名的图片和.txt文件
                foreach ($imageFiles as $imageFile) {
                    $baseName = pathinfo($imageFile, PATHINFO_FILENAME);
                    // 检查是否为缩略图
                    if (strpos($baseName, '-thumb') !== false) {
                        continue;
                    }
                    $txtFile = $baseName . '.txt';
                    
                    if (in_array($txtFile, $txtFiles)) {
                        // 读取TXT文件
                        $txtContent = file_get_contents($tempPath . '/' . $txtFile);
                        
                        // 查找缩略图
                        $thumbnail = null;
                        $thumbWebp = $baseName . '-thumb.webp';
                        $thumbJpg = $baseName . '-thumb.jpg';
                        
                        if (in_array($thumbWebp, $rootFiles)) {
                            $thumbnail = $tempPath . '/' . $thumbWebp;
                        } elseif (in_array($thumbJpg, $rootFiles)) {
                            $thumbnail = $tempPath . '/' . $thumbJpg;
                        }
                        
                        if ($txtContent !== false) {
                            // 获取文件创建时间
                            $fileTime = filemtime($tempPath . '/' . $imageFile);
                            $createdDate = date('Y-m-d', $fileTime);
                            
                            // 解析txt文件内容
                            $parsedData = parseTxtContent($txtContent);
                            
                            $works[] = [
                                'id' => $baseName,
                                'imageName' => $parsedData['imageName'] ?? $baseName,
                                'category' => '根目录',
                                'thumbnail' => $thumbnail ?: $tempPath . '/' . $imageFile,
                                'imageUrl' => $tempPath . '/' . $imageFile,
                                'txtContent' => $txtContent,
                                'parsedData' => $parsedData,
                                'created' => $createdDate,
                                'filePath' => $tempPath . '/' . $imageFile
                            ];
                        }
                    }
                }
                
                // 处理子目录
                foreach ($rootFiles as $item) {
                    if ($item != '.' && $item != '..' && is_dir($tempPath . '/' . $item) && !in_array($item, $excludedFolders)) {
                        $category = $item;
                        $categoryPath = $tempPath . '/' . $category;
                        $categoryFiles = scandir($categoryPath);
                        $categoryImageFiles = [];
                        $categoryTxtFiles = [];
                        
                        // 分离图片和txt文件
                        foreach ($categoryFiles as $file) {
                            if ($file != '.' && $file != '..') {
                                $extension = pathinfo($file, PATHINFO_EXTENSION);
                                if (in_array($extension, ['webp', 'jpg', 'png', 'jpeg'])) {
                                    $categoryImageFiles[] = $file;
                                } elseif ($extension === 'txt') {
                                    $categoryTxtFiles[] = $file;
                                }
                            }
                        }
                        
                        // 匹配同名的图片和.txt文件
                        foreach ($categoryImageFiles as $imageFile) {
                            $baseName = pathinfo($imageFile, PATHINFO_FILENAME);
                            // 检查是否为缩略图
                            if (strpos($baseName, '-thumb') !== false) {
                                continue;
                            }
                            $txtFile = $baseName . '.txt';
                            
                            if (in_array($txtFile, $categoryTxtFiles)) {
                                // 读取TXT文件
                                $txtContent = file_get_contents($categoryPath . '/' . $txtFile);
                                
                                // 查找缩略图
                                $thumbnail = null;
                                $thumbWebp = $baseName . '-thumb.webp';
                                $thumbJpg = $baseName . '-thumb.jpg';
                                
                                if (in_array($thumbWebp, $categoryFiles)) {
                                    $thumbnail = $categoryPath . '/' . $thumbWebp;
                                } elseif (in_array($thumbJpg, $categoryFiles)) {
                                    $thumbnail = $categoryPath . '/' . $thumbJpg;
                                }
                                
                                if ($txtContent !== false) {
                                    // 获取文件创建时间
                                    $fileTime = filemtime($categoryPath . '/' . $imageFile);
                                    $createdDate = date('Y-m-d', $fileTime);
                                    
                                    // 解析txt文件内容
                                    $parsedData = parseTxtContent($txtContent);
                                    
                                    $works[] = [
                                        'id' => $baseName,
                                        'imageName' => $parsedData['imageName'] ?? $baseName,
                                        'category' => $category,
                                        'thumbnail' => $thumbnail ?: $categoryPath . '/' . $imageFile,
                                        'imageUrl' => $categoryPath . '/' . $imageFile,
                                        'txtContent' => $txtContent,
                                        'parsedData' => $parsedData,
                                        'created' => $createdDate,
                                        'filePath' => $categoryPath . '/' . $imageFile
                                    ];
                                }
                            }
                        }
                    }
                }
                
                // 按创建时间排序（最新在前）
                usort($works, function($a, $b) {
                    return strtotime($b['created']) - strtotime($a['created']);
                });
                
                // 只显示前8个作品
                $displayedWorks = array_slice($works, 0, 8);
                
                // 输出作品卡片
                if (count($displayedWorks) > 0) {
                    foreach ($displayedWorks as $work) {
                        echo '<div class="card group animate-fade-in-up">';
                        echo '<div class="thumbnail-container">';
                        echo '<img src="' . htmlspecialchars($work['thumbnail']) . '" alt="' . htmlspecialchars($work['imageName']) . '" class="thumbnail">';
                        echo '<div class="category-tag">' . htmlspecialchars($work['category']) . '</div>';
                        echo '</div>';
                        echo '<div class="card-content">';
                        echo '<h3 class="card-title">' . htmlspecialchars($work['imageName']) . '</h3>';
                        echo '<div class="card-meta">';
                        echo '<span class="date">' . htmlspecialchars($work['created']) . '</span>';
                        echo '<span class="models">';
                        echo '<i class="fas fa-image text-xs mr-1"></i>';
                        echo '反推图';
                        echo '</span>';
                        echo '</div>';
                        echo '</div>';
                        echo '</div>';
                    }
                } else {
                    echo '<div class="col-span-full text-center py-16">';
                    echo '<div class="inline-block p-6 bg-gray-100 dark:bg-gray-800 rounded-2xl mb-6">';
                    echo '<i class="fas fa-image text-6xl text-gray-400"></i>';
                    echo '</div>';
                    echo '<h3 class="text-2xl font-bold text-gray-700 dark:text-gray-300 mb-2">暂无反推图</h3>';
                    echo '<p class="text-gray-500 dark:text-gray-400">请上传反推图文件或生成缩略图</p>';
                    echo '</div>';
                }
            } else {
                echo '<div class="col-span-full text-center py-16">';
                echo '<div class="inline-block p-6 bg-red-100 dark:bg-red-900/30 rounded-2xl mb-6">';
                echo '<i class="fas fa-exclamation-triangle text-6xl text-red-400"></i>';
                echo '</div>';
                echo '<h3 class="text-2xl font-bold text-red-700 dark:text-red-300 mb-2">output文件夹不存在</h3>';
                echo '<p class="text-gray-500 dark:text-gray-400">请创建output文件夹并添加作品文件</p>';
                echo '</div>';
            }
            
            // 解析txt文件内容的函数
            function parseTxtContent($content) {
                $data = [
                    'chineseDesc' => '',
                    'englishDesc' => '',
                    'chineseTags' => '',
                    'englishTags' => ''
                ];
                
                // 提取中文描述
                if (preg_match('/★★中文描述★★\s*(.*?)\s*(?=■■英文描述■■|$)/s', $content, $matches)) {
                    $data['chineseDesc'] = trim($matches[1]);
                }
                
                // 提取英文描述
                if (preg_match('/■■英文描述■■\s*(.*?)\s*(?=【中文Tag标签】|$)/s', $content, $matches)) {
                    $data['englishDesc'] = trim($matches[1]);
                }
                
                // 提取中文标签
                if (preg_match('/【中文Tag标签】\s*(.*?)\s*(?=\[英文Tag标签\]|$)/s', $content, $matches)) {
                    $data['chineseTags'] = trim($matches[1]);
                }
                
                // 提取英文标签
                if (preg_match('/\[英文Tag标签\]\s*(.*?)\s*$/s', $content, $matches)) {
                    $data['englishTags'] = trim($matches[1]);
                }
                
                return $data;
            }
            ?>
        </div>
        
        <!-- 加载更多按钮 -->
        <div class="mt-12 text-center">
            <?php if (count($works) > 8): ?>
            <button id="load-more" class="load-more-btn">
                <i class="fas fa-spinner fa-spin mr-2 loading-animation hidden"></i>
                <span>加载更多反推图</span>
            </button>
            <?php endif; ?>
        </div>
        
        <!-- 滚动指示器 -->
        <div class="scroll-indicator hidden" id="scroll-indicator">
            <i class="fas fa-arrow-down"></i>
        </div>
    </main>

    <!-- 作品详情模态框 -->
    <div class="fixed inset-0 bg-black bg-opacity-60 z-50 flex items-center justify-center p-4 hidden" id="modal">
        <div class="bg-white dark:bg-gray-800 rounded-2xl max-w-5xl w-full max-h-screen overflow-y-auto animate-fade-in-up">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title" id="modal-title">反推图详情</h3>
                    <button class="modal-close" id="close-modal">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-grid">
                    <div class="modal-image-container">
                        <img src="" alt="作品预览" class="modal-image" id="modal-image">
                    </div>
                    <div>
                        <div class="info-section">
                            <div class="flex justify-between items-center">
                                <h4 class="info-title">中文描述</h4>
                                <button class="copy-btn" data-target="modal-chinese-desc" data-message="中文描述已复制">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                            <div class="prompt-text" id="modal-chinese-desc">
                                <!-- 中文描述将动态填充 -->
                            </div>
                        </div>
                        
                        <div class="info-section">
                            <div class="flex justify-between items-center">
                                <h4 class="info-title">英文描述</h4>
                                <button class="copy-btn" data-target="modal-english-desc" data-message="英文描述已复制">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                            <div class="prompt-text" id="modal-english-desc">
                                <!-- 英文描述将动态填充 -->
                            </div>
                        </div>
                        
                        <div class="info-section">
                            <div class="flex justify-between items-center">
                                <h4 class="info-title">中文Tag标签</h4>
                                <button class="copy-btn" data-target="modal-chinese-tags" data-message="中文Tag标签已复制">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                            <div class="prompt-text" id="modal-chinese-tags">
                                <!-- 中文标签将动态填充 -->
                            </div>
                        </div>
                        
                        <div class="info-section">
                            <div class="flex justify-between items-center">
                                <h4 class="info-title">英文Tag标签</h4>
                                <button class="copy-btn" data-target="modal-english-tags" data-message="英文Tag标签已复制">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </div>
                            <div class="prompt-text" id="modal-english-tags">
                                <!-- 英文标签将动态填充 -->
                            </div>
                        </div>
                        
                        <div class="info-section">
                            <h4 class="info-title">基本信息</h4>
                            <div class="space-y-3">
                                <div class="info-item">
                                    <span class="info-label">名称:</span>
                                    <span class="info-value" id="modal-image-name"></span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">类别:</span>
                                    <span class="info-value" id="modal-category"></span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">创建时间:</span>
                                    <span class="info-value" id="modal-created"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 从PHP获取作品数据
        const worksData = <?php echo json_encode($works); ?>;
        let currentCategory = '根目录';
        let displayedCount = 8;
        let isLoading = false;
        let isDarkMode = false;

        // DOM元素
        const galleryGrid = document.getElementById('gallery-grid');
        const loadMoreBtn = document.getElementById('load-more');
        const modal = document.getElementById('modal');
        const closeModalBtn = document.getElementById('close-modal');
        const themeToggle = document.getElementById('theme-toggle');
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const mobileMenu = document.getElementById('mobile-menu');
        const scrollIndicator = document.getElementById('scroll-indicator');
        const categoryButtons = document.querySelectorAll('.category-btn');

        // 初始化应用
        function initApp() {
            // 默认浅色模式
            document.body.classList.add('light-mode');
            
            // 绑定事件监听器
            bindEventListeners();
            
            // 显示滚动指示器
            showScrollIndicator();
            
            // 为作品卡片添加点击事件
            addCardClickEvents();
        }

        // 为作品卡片添加点击事件
        function addCardClickEvents() {
            document.querySelectorAll('.card').forEach(card => {
                card.addEventListener('click', function() {
                    // 找到对应的work数据
                    const cardTitle = this.querySelector('.card-title').textContent;
                    const work = worksData.find(w => w.imageName === cardTitle);
                    if (work) {
                        openModal(work);
                    }
                });
            });
        }

        // 绑定事件监听器
        function bindEventListeners() {
            // 加载更多按钮
            if (loadMoreBtn) {
                loadMoreBtn.addEventListener('click', loadMoreWorks);
            }
            
            // 关闭模态框
            closeModalBtn.addEventListener('click', closeModal);
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    closeModal();
                }
            });
            
            // 键盘导航
            document.addEventListener('keydown', handleKeyboardNavigation);
            
            // 主题切换
            themeToggle.addEventListener('click', toggleDarkMode);
            
            // 移动端菜单
            mobileMenuButton.addEventListener('click', toggleMobileMenu);
            
            // 类别筛选
            categoryButtons.forEach(button => {
                button.addEventListener('click', function() {
                    categoryButtons.forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');
                    currentCategory = this.getAttribute('data-category');
                    resetDisplayedCount();
                    filterAndLoadWorks();
                });
            });
            
            // 滚动事件
            window.addEventListener('scroll', handleScroll);
            
            // 窗口大小改变
            window.addEventListener('resize', handleResize);
            
            // 添加复制按钮事件监听器
            document.addEventListener('click', function(e) {
                if (e.target.closest('.copy-btn')) {
                    copyToClipboard(e.target.closest('.copy-btn'));
                }
            });
        }

        // 复制到剪贴板功能
        function copyToClipboard(button) {
            const targetId = button.getAttribute('data-target');
            const message = button.getAttribute('data-message');
            const targetElement = document.getElementById(targetId);
            
            if (targetElement) {
                // 创建一个临时的textarea元素来复制内容
                const textarea = document.createElement('textarea');
                textarea.value = targetElement.textContent.trim();
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                
                // 显示复制成功的提示
                showCopyNotification(message);
            }
        }

        // 显示复制成功的提示
        function showCopyNotification(message) {
            // 创建提示元素
            const notification = document.createElement('div');
            notification.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50 transition-opacity duration-300';
            notification.textContent = message;
            notification.style.opacity = '0';
            
            document.body.appendChild(notification);
            
            // 渐显动画
            setTimeout(() => {
                notification.style.opacity = '1';
            }, 10);
            
            // 3秒后自动移除
            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }

        // 处理键盘导航
        function handleKeyboardNavigation(e) {
            if (e.key === 'Escape' && modal.classList.contains('hidden') === false) {
                closeModal();
            } else if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
                window.scrollBy({ top: 300, behavior: 'smooth' });
            } else if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') {
                window.scrollBy({ top: -300, behavior: 'smooth' });
            }
        }

        // 切换暗色模式
        function toggleDarkMode() {
            isDarkMode = !isDarkMode;
            if (isDarkMode) {
                document.body.classList.remove('light-mode');
                document.body.classList.add('dark-mode');
                themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
            } else {
                document.body.classList.remove('dark-mode');
                document.body.classList.add('light-mode');
                themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
            }
        }

        // 切换移动端菜单
        function toggleMobileMenu() {
            mobileMenu.classList.toggle('hidden');
        }

        // 处理滚动
        function handleScroll() {
            // 隐藏滚动指示器
            if (window.scrollY > 200) {
                scrollIndicator.classList.add('hidden');
            }
            
            // 无限滚动 - 当接近页面底部时自动加载更多
            if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500 && !isLoading && loadMoreBtn && loadMoreBtn.classList.contains('hidden') === false) {
                loadMoreWorks();
            }
        }

        // 处理窗口大小改变
        function handleResize() {
            if (window.innerWidth >= 768) {
                mobileMenu.classList.add('hidden');
            }
        }

        // 显示滚动指示器
        function showScrollIndicator() {
            setTimeout(() => {
                if (window.scrollY < 200) {
                    scrollIndicator.classList.remove('hidden');
                }
            }, 2000);
        }

        // 重置显示数量
        function resetDisplayedCount() {
            displayedCount = 8;
            galleryGrid.innerHTML = '<div class="col-span-full text-center py-12"><div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-600"></div><p class="mt-4 text-gray-600 dark:text-gray-400">正在加载反推图...</p></div>';
        }

        // 筛选并加载作品
        function filterAndLoadWorks() {
            // 获取筛选后的作品
            let filteredWorks = [];
            
            if (currentCategory === '根目录') {
                filteredWorks = worksData.filter(work => work.category === '根目录');
            } else {
                filteredWorks = worksData.filter(work => work.category === currentCategory);
            }
            
            // 按创建时间排序（最新在前）
            filteredWorks.sort((a, b) => new Date(b.created) - new Date(a.created));
            
            // 只显示指定数量的作品
            const limitedWorks = filteredWorks.slice(0, displayedCount);
            
            // 渲染作品
            setTimeout(() => {
                renderWorks(limitedWorks);
                
                // 更新加载更多按钮状态
                if (filteredWorks.length <= displayedCount) {
                    if (loadMoreBtn) loadMoreBtn.classList.add('hidden');
                } else {
                    if (loadMoreBtn) loadMoreBtn.classList.remove('hidden');
                }
            }, 500);
        }

        // 加载更多作品
        function loadMoreWorks() {
            if (isLoading) return;
            
            isLoading = true;
            if (loadMoreBtn) {
                loadMoreBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i><span>加载中...</span>';
            }
            
            // 模拟加载延迟
            setTimeout(() => {
                displayedCount += 8;
                filterAndLoadWorks();
                isLoading = false;
                if (loadMoreBtn) {
                    loadMoreBtn.innerHTML = '<span>加载更多反推图</span>';
                }
            }, 800);
        }

        // 渲染作品
        function renderWorks(works) {
            galleryGrid.innerHTML = '';
            
            if (works.length === 0) {
                galleryGrid.innerHTML = `
                    <div class="col-span-full text-center py-16">
                        <div class="inline-block p-6 bg-gray-100 dark:bg-gray-800 rounded-2xl mb-6">
                            <i class="fas fa-search text-6xl text-gray-400"></i>
                        </div>
                        <h3 class="text-2xl font-bold text-gray-700 dark:text-gray-300 mb-2">未找到反推图</h3>
                        <p class="text-gray-500 dark:text-gray-400">请尝试其他分类或上传新作品</p>
                    </div>
                `;
                return;
            }
            
            works.forEach(work => {
                const workCard = document.createElement('div');
                workCard.className = 'card group animate-fade-in-up';
                workCard.innerHTML = `
                    <div class="thumbnail-container">
                        <img src="${work.thumbnail}" alt="${work.imageName}" class="thumbnail">
                        <div class="category-tag">${work.category}</div>
                    </div>
                    <div class="card-content">
                        <h3 class="card-title">${work.imageName}</h3>
                        <div class="card-meta">
                            <span class="date">${work.created}</span>
                            <span class="models">
                                <i class="fas fa-image text-xs mr-1"></i>
                                反推图
                            </span>
                        </div>
                    </div>
                `;
                
                // 添加点击事件
                workCard.addEventListener('click', function() {
                    openModal(work);
                });
                
                galleryGrid.appendChild(workCard);
            });
        }

        // 打开模态框
        function openModal(work) {
            document.getElementById('modal-title').textContent = work.imageName;
            document.getElementById('modal-image-name').textContent = work.imageName;
            document.getElementById('modal-category').textContent = work.category;
            document.getElementById('modal-created').textContent = work.created;
            document.getElementById('modal-image').src = work.imageUrl;
            document.getElementById('modal-chinese-desc').textContent = work.parsedData.chineseDesc || "无";
            document.getElementById('modal-english-desc').textContent = work.parsedData.englishDesc || "无";
            document.getElementById('modal-chinese-tags').textContent = work.parsedData.chineseTags || "无";
            document.getElementById('modal-english-tags').textContent = work.parsedData.englishTags || "无";
            
            modal.classList.remove('hidden');
            document.body.style.overflow = 'hidden';
        }

        // 关闭模态框
        function closeModal() {
            modal.classList.add('hidden');
            document.body.style.overflow = 'auto';
        }

        // 初始化应用
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>